package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**登录检查过滤器
 * @author zhoufei
 */
@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("登录检查过滤器执行。。。。");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求路径
        String requestURI = request.getRequestURI();

        //2.判断本次请求是否在白名单中
        //2.1创建请求白名单
        String [] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2.2判断本次请求是否存在白名单中，创建一个方法
        Boolean check = check(urls, requestURI);
        if (check){
            //存在白名单中，不需要处理放行
            filterChain.doFilter(request,response);
            return;
        }

        Long empId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");
        //3.判断登录状态，已经登录直接放行
        if (empId != null){
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        if(userId != null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //4.未登录，则返回结果，在前端页面进行跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private Boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
